import 'package:app/api/command/index.dart';
import 'package:app/components/index.dart';
import 'package:flutter/material.dart';
import 'package:qrscan/qrscan.dart' as scanner;

class Carrying extends StatefulWidget {
  const Carrying({super.key});

  @override
  State<Carrying> createState() => _CarryingState();
}

/// 托盘搭载
class _CarryingState extends State<Carrying> {
  final GlobalKey<FormState>? _formKey = GlobalKey<FormState>();

  double _height = 200;

  String _code = "";

  String _agvCode = "";

  final FocusNode _firstFocusNode = FocusNode();

  final FocusNode _secondFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    // 在初始化时将焦点放在第一个文本框上
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_firstFocusNode);
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _firstFocusNode.dispose();
  }

  void hideKeyBorder() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  void scan(String key) async{
    String? qrCode = await scanner.scan();
    if (key == 'agvCode') {
      setState(() => _agvCode = qrCode.toString());
    } else if (key == 'code') {
      setState(() => _code = qrCode.toString());
    }
  }

  void setValue(key, value){
    switch(key){
      case '_code': setState(() => _code = value); break;
      case '_agvCode': setState(() => _agvCode = value); break;
      default:
        throw Exception('error key');
    }
  }

  void clear(){
    setState(() {
      _code = "";
      _agvCode = "";
    });
  }

  /// 开始搭载
  void submit(){
    Forms.validate(_formKey!).then((valid){
        if(valid){
          setState(() => _height = 200);
          /// 执行搭载接口
          Command.of(context).carrying({'agvCode': _agvCode, 'endStation': _code}).then((res){
            if(res?.data?['code'] == 'success'){
              clear();
              Success.of(context).show('调用成功，等待搭载');
            }
          });
        }else{
          setState(() => _height = 280);
        }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBars(title: '托盘搭载', context: context),
        body: GestureDetector(
            onTap: hideKeyBorder,
            child: Column(children: [
              Group(
                  title: '车辆信息',
                  height: _height,
                  width: MediaQuery.of(context).size.width,
                  context: context,
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Forms(
                            formKey: _formKey,
                            formItem: [
                              FormItem(
                                onEntry: (String value)=>{
                                  FocusScope.of(context).requestFocus(_secondFocusNode)
                                },
                                type: 'input',
                                labelText: '车辆编码',
                                placeholder: '请扫描车辆编码',
                                filedName: 'agvCode',
                                focusNode: _firstFocusNode,
                                iconOnTap: () => scan('agvCode'),
                                value: _agvCode,
                                labelWidth: 90,
                                icon: const Icon(Icons.qr_code_scanner_rounded),
                                onChange: (value) => setValue('_agvCode', value),
                                rules: const {'agvCode': [{'required': true, 'message': '车辆编码不能为空'}]},
                              ),
                              FormItem(
                                type: 'input',
                                labelText: '地码',
                                placeholder: '请扫描地码',
                                filedName: 'code',
                                iconOnTap: () => scan('code'),
                                focusNode: _secondFocusNode,
                                value: _code,
                                labelWidth: 90,
                                icon: const Icon(Icons.qr_code_scanner_rounded),
                                onChange: (value) => setValue('_code', value),
                                rules: const {'code': [{'required': true, 'message': '地码不能为空'}]},
                              ),
                            ]
                        ),
                        Padding(
                            padding: const EdgeInsets.only(top: 10, right: 10),
                            child: Button(
                              label: '清空',
                              icon: Icons.delete_forever,
                              onPressed: clear,
                              fontColor: Colors.black,
                              backgroundColor: Colors.white,
                              borderColor: const Color.fromARGB(255, 133, 133, 133),
                            ),
                        ),
                      ]
                  ),
              ),
              SizedBox(
                width: MediaQuery.of(context).size.width,
                child: Padding(
                  padding: const EdgeInsets.only(top: 50, left: 20, right: 20),
                  child: Button(
                    onPressed: submit,
                    label: '开始搭载',
                    height: 60,
                    fontSize: 18,
                  ),
                ),
              ),
            ])));
  }
}
